/**
 * This file is part of ${project_name}.
 * 
 * ${project_name} is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 * 
 * ${project_name} is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * ${project_name}. If not, see <http://www.gnu.org/licenses/>.
 * 
 * @see http://www.gnu.org/licenses/lgpl.txt
 * @author art <lijianghui2000@gmail.com>
 */
package com.life.android.audiotageditor.activity;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.life.android.audiotageditor.R;
import com.life.android.audiotageditor.constants.Constants;
import com.life.android.audiotageditor.model.AudioFolder;
import com.life.android.audiotageditor.model.AudioModel;
import com.life.android.audiotageditor.model.AudioModelManager;
import com.life.android.audiotageditor.model.IAudioModel;

public class AudioTagEditor extends ListActivity {

	private AudioModel audioModel = (AudioModel) AudioModelManager.instance()
			.getRoot();

	private AudioFolder sdCardRoot;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		sdCardRoot = (AudioFolder) audioModel.getFolder(Environment
				.getExternalStorageDirectory().getPath());
		fillContent(sdCardRoot);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Map<String, Object> item = (Map<String, Object>) l
				.getItemAtPosition(position);
		int itemType = (Integer) item.get("type");
		if (itemType == IAudioModel.AUDIO_FOLDER) {
			fillContent((AudioFolder) audioModel.getFolder(item.get("path")
					.toString()));
		}
		if (itemType == IAudioModel.AUDIO_FILE) {
			Intent intent = new Intent();
			intent.putExtra("audioFilePath", item.get("path").toString());
			intent.setClass(this, Audio.class);
			startActivity(intent);
		}
		super.onListItemClick(l, v, position, id);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.aboutMenu:
			startActivity(new Intent(this, About.class));
			return true;
		case R.id.exitMenu:
			finish();
			return true;
		}
		return false;
	}

	private void fillContent(AudioFolder audioFolder) {
		List<Map<String, Object>> fileNames = getFileNames(audioFolder);

		SimpleAdapter simpleAdapter = new SimpleAdapter(this, fileNames,
				R.layout.main, new String[] { "icon", "name", "path", "type" },
				new int[] { R.id.icon, R.id.name, R.id.path, R.id.type });
		this.setListAdapter(simpleAdapter);
	}

	@SuppressWarnings("unchecked")
	private <V> List<Map<String, V>> getFileNames(AudioFolder audioFolder) {
		List<Map<String, V>> result = new ArrayList<Map<String, V>>();
		if (!sdCardRoot.equals(audioFolder)) {
			Map<String, V> backMap = new HashMap<String, V>();
			backMap.put("icon", (V) new Integer(R.drawable.back));
			backMap.put("name", (V) Constants.STRING_NONE);
			backMap.put("path", (V) audioFolder.getParent().getFullPath());
			backMap.put("type", (V) new Integer(IAudioModel.AUDIO_FOLDER));
			result.add(backMap);
		}
		IAudioModel[] children = audioFolder.members();
		if (children == null) {
			return result;
		}
		for (IAudioModel child : children) {
			Map<String, V> map = new HashMap<String, V>();
			int childType = child.getType();
			map.put("icon", (V) new Integer(
					childType == IAudioModel.AUDIO_FOLDER ? R.drawable.folder
							: R.drawable.songs));
			map.put("name", (V) child.getName());
			map.put("path", (V) child.getFullPath());
			map.put("type", (V) new Integer(childType));
			result.add(map);
		}
		sortResult(result);
		return result;
	}

	private <V> void sortResult(List<Map<String, V>> result) {
		List<Map<String, V>> folderItems = new ArrayList<Map<String, V>>();
		List<Map<String, V>> fileItems = new ArrayList<Map<String, V>>();
		for (Map<String, V> item : result) {
			V type = item.get("type");
			switch ((Integer) type) {
			case IAudioModel.AUDIO_FOLDER:
				folderItems.add(item);
				break;
			case IAudioModel.AUDIO_FILE:
				fileItems.add(item);
				break;
			}
		}

		final Collator chinaCollator = Collator
				.getInstance(java.util.Locale.CHINA);
		Collections.sort(folderItems, new Comparator<Map<String, V>>() {
			@Override
			public int compare(Map<String, V> map1, Map<String, V> map2) {
				String name1 = map1.get("name").toString();
				String name2 = map2.get("name").toString();
				return chinaCollator.compare(name1.toLowerCase(),
						name2.toLowerCase());
			}
		});
		Collections.sort(fileItems, new Comparator<Map<String, V>>() {
			@Override
			public int compare(Map<String, V> map1, Map<String, V> map2) {
				String name1 = map1.get("name").toString();
				String name2 = map2.get("name").toString();
				return chinaCollator.compare(name1.toLowerCase(),
						name2.toLowerCase());
			}
		});

		result.clear();
		result.addAll(folderItems);
		result.addAll(fileItems);
	}
}